package com.jz.community.moduleshopping.goodsDetail.ui.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jz.community.basecomm.bean.ShareInfo;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.reflection.share.ShareActionReflectUtils;
import com.jz.community.basecomm.reflection.share.ShareClickListener;
import com.jz.community.basecomm.utils.BaseImageLoaderUtils;
import com.jz.community.basecomm.utils.CharacterUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.RxTextTool;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.goodsDetail.bean.GoodsDetailInfo;
import com.jz.community.sharesdk.share.ShareApi;
import com.zyyoona7.popup.EasyPopup;

import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Tony.Fan on 2018/9/6 09:18
 */
public class ShareGoodsPopUp {

    private EasyPopup easyPopup;

    private Context context;
    private ImageView share_goods_image_iv;
    private TextView share_goods_subject;
    private TextView share_goods_price_tv;
    private TextView share_goods_strike_price_tv;
    private ImageView share_goods_scan_btn;
    private LinearLayout share_layout;
    private Button save_share_iv;
    private GoodsDetailInfo mGoodsDetailInfo;
    private ShareInfo shareInfo;
    private Bitmap bmp;

    public ShareGoodsPopUp(Context context) {
        this.context = context;
    }

    public void addGoodsDetailInfo(GoodsDetailInfo goodsDetailInfo) {
        mGoodsDetailInfo = goodsDetailInfo;
        initPop(context);
    }

    private void initPop(Context context) {
        easyPopup = EasyPopup.create()
                .setContentView(context, R.layout.share_goods_layout)
                .setAnimationStyle(R.style.RightTop2PopAnim)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                //允许背景变暗
                .setBackgroundDimEnable(true)
                //变暗的透明度(0-1)，0为完全透明
                .setDimValue(0.4f)
                .setOnViewListener(new EasyPopup.OnViewListener() {
                    @Override
                    public void initViews(View view) {
                        initView(view);
                    }
                })
                .apply();
    }

    private void initView(View view) {
        share_goods_image_iv = view.findViewById(R.id.share_goods_image_iv);
        share_goods_subject = view.findViewById(R.id.share_goods_subject);
        share_goods_price_tv = view.findViewById(R.id.share_goods_price_tv);
        share_goods_strike_price_tv = view.findViewById(R.id.share_goods_strike_price_tv);
        share_goods_scan_btn = view.findViewById(R.id.share_goods_scan_btn);
        share_layout = view.findViewById(R.id.share_goode_layout);
        save_share_iv = view.findViewById(R.id.save_share_iv);
        BaseImageLoaderUtils.getInstance().loadDefaltImage(context, share_goods_image_iv, mGoodsDetailInfo.getImage().get(0));
        share_goods_subject.setText(mGoodsDetailInfo.getTitle());
        // 获取图片某布局
        share_layout.setDrawingCacheEnabled(true);
        share_layout.buildDrawingCache();
        shareInfo = new ShareInfo();
        handleShareGoodsLayout();
        makeShareGoodEncode(mGoodsDetailInfo.getQrCodeLink());
        GoodsDetailInfo.SkuInfosBean skuInfos = mGoodsDetailInfo.getSkuInfos().get(0);
        if (!Preconditions.isNullOrEmpty(skuInfos.getDiscountPrice()) && !Preconditions.isNullOrEmpty(skuInfos.getPrice())) {
            share_goods_price_tv.setText(AppConstants.MONEY + skuInfos.getDiscountPrice());
            SHelper.vis(share_goods_strike_price_tv);
            RxTextTool.getBuilder("").append(CharacterUtils.roundByGoodPrice(ConverterUtils.toDouble(skuInfos.getPrice()))).setStrikethrough().into(share_goods_strike_price_tv);
        } else if (!Preconditions.isNullOrEmpty(skuInfos.getDiscountPrice())) {
            share_goods_price_tv.setText(AppConstants.MONEY + skuInfos.getDiscountPrice());
        } else {
            share_goods_price_tv.setText(AppConstants.MONEY + skuInfos.getPrice());
        }
        save_share_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler().postDelayed(() -> {
                    easyPopup.dismiss();
                }, 100);
                ShareActionReflectUtils.jumpSharerPage(context, shareInfo, new ShareClickListener() {
                    @Override
                    public void shareClickResult() {
                        shareInfo.setLink(mGoodsDetailInfo.getGoodsUrlSale());
                        shareInfo.setSubject(mGoodsDetailInfo.getTitle());
                        shareInfo.setText(mGoodsDetailInfo.getContent());
                        shareInfo.setImageUrl(mGoodsDetailInfo.getImage().get(0));
                        ShareApi.getInstance().shareWeiXinSmallRoutine((Activity) context, shareInfo);
                    }
                });
            }
        });
    }

    @SuppressLint("CheckResult")
    private void makeShareGoodEncode(String goodShareScan) {
        Observable.just(goodShareScan)
                .map(new Function<String, Bitmap>() {
                    @Override
                    public Bitmap apply(String s) throws Exception {
                        return QRCodeEncoder.syncEncodeQRCode(s, 320, Color.parseColor("#000000"));
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((Bitmap bm) -> {
                    share_goods_scan_btn.setImageBitmap(bm);
                });
    }

    private void handleShareGoodsLayout() {
        new Handler().postDelayed(() -> {
            bmp = share_layout.getDrawingCache();
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 480, 800, true);
            shareInfo.setBitmap(thumbBmp);
        }, 100);
    }

    public void showGoodsSharePopUp(View view) {
        if (easyPopup != null && easyPopup.isShowing()) {
            easyPopup.dismiss();
        } else {
            easyPopup.showAtLocation(view, Gravity.CENTER, 0, 0);
            handleShareGoodsLayout();
        }
    }
}
